package com.cloud.cop.marshaller;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.cloud.cop.CopResponse;
import com.cloud.cop.CopResponseMarshaller;


/**
 * <pre>
 * 功能说明
 * </pre>
 * @author 马永华
 * @version 1.0
 */
public  class JaxbXmlCopResponseMarshaller implements CopResponseMarshaller{

	private static Map<Class,Marshaller> marshallerMap = new HashMap<Class,Marshaller>();
	
	public void marshaller(CopResponse response, OutputStream outputStream) {
		try {
			Marshaller marshaller = getMarshaller(response);
			marshaller.marshal(response, outputStream);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	
	private Marshaller getMarshaller(CopResponse response) throws JAXBException {
		if(!marshallerMap.containsKey(response.getClass())){
			 JAXBContext context = JAXBContext.newInstance(response.getClass());
             Marshaller marshaller = context.createMarshaller();
             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
             marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
             marshallerMap.put(response.getClass(), marshaller);
		}
		return marshallerMap.get(response.getClass());
	}
}

